let common = {};
let _baseURL = 'http://47.109.140.2:8991';

common.api = (opt) => {
	let header = { 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8' };
	if (uni.getStorageSync('token') && uni.getStorageSync('token') != '') {
		header = {
			'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
			'token': uni.getStorageSync('token')
		};
	}
	if (opt.method != 'GET') {
		uni.showLoading();
	}
	uni.request({
	    url: _baseURL + (opt.url || ''),
	    data: opt.data || null,
		method: opt.method,
	    header: header,
	    success: (res) => {
			if (opt.method != 'GET') {
				uni.hideLoading();
			}
			if (res.data.code == 4000 || res.data.code == 4001 || res.data.code == 4002 || res.data.code == 4003 || res.data.code == 4004) {
				uni.removeStorageSync('token');
				uni.reLaunch({url:'/pages/login/index'})
			} else {
				if (res.data.code == 6000) {
					uni.showToast({ title: res.data.msg, icon: 'none' });
				}
				opt.success(res.data);
			}
	    },
		fail: (res) => {
			if (opt.method != 'GET') {
				uni.hideLoading();
			}
			console.log(res)
		}
	});
}

common.getUrlKey = function (name) {
	let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	let r = window.location.href.split('?')[1]?window.location.href.split('?')[1].match(reg):null;
	if(r!=null)return  unescape(r[2]); return null;
}

common.validator = function(rules, form) {
	let reg = {
		'mobile': /^1[3|4|5|6|7|8|9]\d{9}$/,     // 手机号
		'idcard': /^\d{6}(19|2\d)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)?$/,     //  身份证号
		'price': /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,    // 价格
		'integer': /(^[1-9]\d*$)/,    // 正整数
		'empty': ''   // 为空
	}
	
	for(let i in rules){
		if (rules[i].rule == 'empty' && form[rules[i].name].toString().replace(/(^\s*)|(\s*$)/g, "") == '') {
			return {validator: false, msg: rules[i].msg};
		} else if (rules[i].rule != 'empty' && !reg[rules[i].rule].test(form[rules[i].name])) {
			return {validator: false, msg: rules[i].msg};
		}
	}
	return {validator: true, msg: ''};
}

common.format = function(time) {
	let d = parseInt(time / 24 / 60 / 60)
	let h = parseInt((time - d*24*60*60) / 60 / 60)
	let m = parseInt((time - d*24*60*60 - h*60*60) / 60)
	let s = parseInt((time - d*24*60*60 - h*60*60) % 60)
	
	let text = (d>0?d+'天':'')+(h>0?h+'小时':'')+(m>0?m+'分钟':'')+s+'秒'
	
	return text
}

common.formatTime = function(timestamp, format) {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, '0');
	const day = String(date.getDate()).padStart(2, '0');
	const hours = String(date.getHours()).padStart(2, '0');
	const minutes = String(date.getMinutes()).padStart(2, '0');
	const seconds = String(date.getSeconds()).padStart(2, '0');

	return format.replace('YYYY', year)
				 .replace('MM', month)
				 .replace('DD', day)
				 .replace('HH', hours)
				 .replace('mm', minutes)
				 .replace('ss', seconds);
}

export default common;